package in.jiemin.springboot.thrift.config;

import in.jiemin.springboot.service.HelloService;
import in.jiemin.springboot.thrift.service.HelloServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Configuration
public class ThriftConfig {

    ExecutorService executorService = Executors.newSingleThreadExecutor();


    @Bean
    public TServerTransport tServerTransport(){
        try {
            return new TServerSocket(7911);
        } catch (TTransportException e) {
            log.info("thrift 绑定端口失败: {}", e.getMessage());
        }
        return null;
    }

    @Bean
    public TServer tServer(){
        // 发布 hello 服务
        HelloService.Processor processor = new HelloService.Processor(new HelloServiceImpl());

        TServer tServer = new TThreadPoolServer(new TThreadPoolServer.Args(
                tServerTransport()).processor(processor));

        return tServer;

    }

    @PostConstruct
    public void init(){
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                // 开启一个线程 运行 thrift server
                tServer().serve();
            }
        });
    }


}
